package com.weimob.cloud.api.config.impl;

import cn.hutool.core.util.StrUtil;
import com.weimob.cloud.api.config.WeimobAccessTokenStorageConfig;
import com.weimob.cloud.api.token.rsp.WeimobAccessTokenRsp;
import lombok.NonNull;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 微盟 Redis 默认存储实现类
 */
public class WeimobAccessTokenRedisStorageConfigImpl implements WeimobAccessTokenStorageConfig {

    private static final String DEFAULT_REDIS_KEY = "weimob:access_token";
    private static final Object LOCK = new Object();

    private final StringRedisTemplate redisTemplate;
    private final String redisKey;

    public WeimobAccessTokenRedisStorageConfigImpl(@NonNull StringRedisTemplate redisTemplate, String redisKey) {
        this.redisTemplate = redisTemplate;
        if (StrUtil.isBlank(redisKey)) {
            this.redisKey = DEFAULT_REDIS_KEY;
        } else {
            this.redisKey = redisKey;
        }
    }

    @Override
    public String getAccessToken() {
        return redisTemplate.opsForValue().get(redisKey);
    }

    @Override
    public void setAccessToken(WeimobAccessTokenRsp accessTokenRsp) {
        if (accessTokenRsp.getExpiresIn() < 5) {
            // token有效期太短，下次重新获取
            return;
        }

        synchronized (LOCK) {
            redisTemplate.opsForValue().set(redisKey, accessTokenRsp.getAccessToken());
            redisTemplate.expire(redisKey, accessTokenRsp.getExpiresIn() - 60, TimeUnit.SECONDS);
        }
    }
}
